package demo.validation;

import demo.common.ResultJson;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

// 用于验证学生信息的控制器
@Controller
public class ValidateStudentController {
    @GetMapping("/validate-student")
    public String addUser(Model model) {
        model.addAttribute("student", new Student());
        return "validation/student";
    }

    @PostMapping("/validate-student")
    public String addUser(@Valid @ModelAttribute("student") Student s, BindingResult bindingResult) {
        for (var v : bindingResult.getFieldErrors()) {
            System.out.println(v.getField()+  " = " + v.getDefaultMessage());
        }
        if (bindingResult.hasErrors()) {
            return "validation/student";
        }
        return "validation/detail";
    }

    @PostMapping("/validate-student-json")
    public String addUser(@Valid @ModelAttribute("student") Student s) {
        return "validation/detail";
    }

    @ExceptionHandler(value = BindException.class)
    public ResponseEntity<ResultJson> bindingException(BindException e) {
        ResultJson resultJson = ResultJson.error().message(e.toString());
        for (var v : e.getFieldErrors()) {
            resultJson.data(v.getField(), v.getDefaultMessage());
        }
        return new ResponseEntity<>(resultJson, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
